<template>
  <el-dialog
    v-model="visible"
    :title="title"
    destroy-on-close
    width="720px"
    @close="handleCancel"
  >
    <el-form
      ref="formRef"
      :model="formState"
      :rules="Rules"
      label-width="100px"
      class="doc-dia"
    >
      <el-form-item label-width="0px" label="" prop="documentName">
        <el-upload
          :accept="acceptTypes"
          :disabled="proparams.dialogType === 'edit'"
          name="uploadFile"
          drag
          ref="upload"
          :limit="1"
          :on-change="handleChange"
          :on-error="handleError"
          :show-file-list="false"
          :auto-upload="true"
        >
          <div class="el-upload__text">
            <div class="download-wrap" v-if="defaultFileList?.length">
              <p
                class="download-text"
                v-for="(item, index) in defaultFileList"
                :key="index"
                @click.stop="handlePreview(item)"
              >
                <i class="snowfont icon-wendang"></i>
                <el-link :underline="false">{{ item?.name }}</el-link>
                <i
                  class="snowfont icon-shanchu"
                  @click.stop="handleRemove(item)"
                  v-if="proparams.dialogType != 'edit'"
                ></i>
                <i class="iconfont team-iconshanchu'"></i>
              </p>
            </div>

            <div v-else><em>点击上传 </em>或拖拽文件到此区域上传</div>
            <div class="el-upload__tip">
              <p>注意：</p>
              <p>
                1、支持上传doc、docx、xls、xlsx、pdf、ppt、pptx、png、jpg、jpeg等格式文件，文件大小不得大于20M；
              </p>
              <!-- <p>1、支持上传doc、docx、xls、xlsx、pdf、ppt、pptx、png、jpg、jpeg、zip、dwg等格式文件,文件大小不得大于20M；</p> -->
              <p>
                2、模型类文件支持上传的格式类型包括：fbx、stl、obj、rvm、bmv、rfa、dgn、dwg、rvt、skp。
              </p>
              <p>3、一次仅支持上传一个文件</p>
            </div>
          </div>
        </el-upload>
        <el-progress v-if="processLoadding" :percentage="loadProgress" />
      </el-form-item>

      <el-form-item
        label="文档名称"
        placeholder="请输入文档名称"
        prop="documentName"
      >
        <el-input
          style="width: 200px"
          v-model="formState.documentName"
          disabled
        />
      </el-form-item>

      <el-form-item
        label="文件类型"
        placeholder="请输入文件类型"
        prop="docTypeName"
      >
        <el-input
          style="width: 200px"
          v-model="formState.docTypeName"
          disabled
        />
      </el-form-item>

      <el-form-item
        label="文档类型"
        placeholder="请选择文档类型"
        prop="documentTypeCode"
      >
        <el-cascader
          :style="{ width: '200px' }"
          v-model="formState.documentTypeCode"
          clearable
          filterable
          :options="documentTypeList"
          :props="documentProp"
          @change="changeType"
          placeholder="输入名称搜索"
        />
      </el-form-item>

      <el-form-item
        label="项目阶段"
        placeholder="请选择项目阶段"
        prop="projectPhaseName"
      >
        <el-select
          :style="{ width: '200px' }"
          v-model="formState.projectPhaseName"
          value-key="dicCode"
        >
          <el-option
            class="default-option"
            v-for="item in projectPhaseList"
            :label="item.dicValue"
            :key="item.dicCode"
            :value="item"
          ></el-option>
        </el-select>
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSure">保存</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, defineProps, defineEmits } from "vue";
import { useRouter } from "vue-router";
import { storageLocal } from "/@/utils/storage";
import NotifMessage from "/@/utils/message/notification";
import { download } from "/@/utils/download";
import * as api from "/@/api/document";
import { uploadBimFile } from "/@/utils/bim";
import { docTypesMatch } from "../types";
import { onFilterFileData, uploadHeaders } from "/@/utils/file";
import { importFileForEcm } from "/@/utils/ecm";
const formRef = ref<HTMLFormElement | null>(null) as any;
const upload = ref<HTMLFormElement | null>(null) as any;
const acceptTypes = ref(
  "model/skp,model/rvt,model/dwg,model/dgn,model/rfa,model/bmv,model/rvm,model/obj,model/fbx,model/stl,image/vnd.dwg,aplication/zip,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/pdf,image/png,image/jpeg,image/jpeg,application/vnd.ms-powerpoint,application/vnd.openxmlformats-officedocument.presentationml.presentation"
);
const proparams = defineProps({
  title: {
    type: String,
    default: "添加文档"
  },

  dialogType: {
    type: String,
    default: "add"
  },

  fileItem: {
    type: Object,
    default: () => {}
  }
});
const documentTypeList = ref([]);
let defaultFileList = ref([]);
const documentProp = ref({
  label: "documentTypeName",
  children: "children",
  value: "documentTypeCode",
  emitPath: false
});
const emit = defineEmits(["cancel", "submit"]);
const title = ref("添加文档");
const projectPhaseList = ref([]);
const dialogType = ref("add");
const router = useRouter();
let targetFile = null;
let formState = reactive({
  docSuffix: "", //文件后缀名
  docTypeName: "", //文件类型名称
  docType: "", //文件类型
  documentAttachmentArr: [],
  documentTypeName: "", //文档类型名称
  documentTypeCode: "", //文档类型编码
  documentName: "", //文档名称
  moduleType: "5",
  projectManageId: "",
  projectName: "",
  projectTypeCode: "",
  remarks: "",
  projectPhaseName: null,
  ext1: storageLocal.getItem("sectionInfo")?.id
});

const loadProgress = ref(0);
const processLoadding = ref(false);

const visible = ref(true);
const Rules = {
  documentName: [{ required: true, message: "请上传文档", trigger: "blur" }],
  // docTypeName: [
  //   { required: true, message: "请输入文件类型", trigger: "blur" }
  // ],
  documentTypeCode: [
    { required: true, message: "请选择文档类型", trigger: "change" }
  ],
  projectPhaseName: [
    { required: true, message: "请选择项目阶段", trigger: "change" }
  ]
  // defaultFileList: [
  //   { required: true, message: "请上传文档", trigger: "change" }
  // ]
};

const initProjectPhaseList = async () => {
  try {
    const params = {
      dicType: "flow_project_phase"
    };
    const { code, data } = await api.postDictList(params);
    projectPhaseList.value = data;
    console.log(code, data);
  } catch (err) {
    console.log(err);
  }
};

const changeType = value => {
  formState.documentTypeCode = value;
  const docObj = getDocTypeAuth(documentTypeList.value, value);
  formState.documentTypeName = docObj.documentTypeName;
};
const getDocTypeAuth = (nodes, searchKey) => {
  for (let _i = 0; _i < nodes.length; _i++) {
    if (nodes[_i].documentTypeCode === searchKey) {
      return nodes[_i];
    } else {
      if (nodes[_i].children && nodes[_i].children.length > 0) {
        const res = getDocTypeAuth(nodes[_i].children, searchKey);
        if (res) {
          return res;
        }
      }
    }
  }
  return null;
};
const onInitFileList = (list: any[]) => {
  if (!list || !list.length || !list[0]?.fileName) return;
  const newFileList = list.map(item => {
    return {
      name: item?.fileName,
      response: {
        data: item,
        code: 200
      }
    };
  });
  return newFileList;
};

if (proparams.title) {
  title.value = proparams.title;
  dialogType.value = proparams.dialogType;
}
if (dialogType.value === "edit") {
  formState = Object.assign(proparams.fileItem);

  defaultFileList.value = onInitFileList(formState.documentAttachmentArr);
}

const handleCancel = () => {
  emit("cancel");
};

const handleSure = async () => {
  const isValid = await new Promise(resolve => formRef.value.validate(resolve));
  if (isValid) {
    formState.documentAttachmentArr = onFilterFileData(defaultFileList.value);

    formState.projectManageId = storageLocal.getItem("projectInfo")?.id;
    formState.projectName = storageLocal.getItem("projectInfo")?.name;
    formState.projectTypeCode =
      storageLocal.getItem("projectInfo")?.projectTypeCode;
    const copyFormData = JSON.parse(JSON.stringify(formState));

    copyFormData.projectPhaseName = formState.projectPhaseName.dicValue;
    copyFormData.projectPhaseCode = formState.projectPhaseName.dicCode;

    emit("submit", copyFormData);
  }
};

/* 上传 -- start */
// const acceptTypes = Object.values(FileTypes).join(",");
// const uploadUrl =
//   import.meta.env.VITE_BASE_URL + "/snow-admin/common/file/upload";
// const uploadHeaders = {
//   Authorization: storageLocal.getItem("info")?.accessToken
// };

const handleRemove = file => {
  upload.value.clearFiles();
  defaultFileList.value = file;
  // defaultFileList.value = defaultFileList.value.filter(item => {
  //   return item.name !== file.name;
  // });
  formState.documentName = "";
  formState.docTypeName = "";
  formState.docType = "";
  formState.docSuffix = "";
};

const handleChange = async file => {
  if (targetFile && targetFile.name === file.name) return;
  targetFile = file;
  const bimTypes = [
    "fbx",
    "stl",
    "obj",
    "rvm",
    "bmv",
    "rfa",
    "dgn",
    "dwg",
    "rvt",
    "skp"
  ];
  const types = [
    "doc",
    "docx",
    "xls",
    "xlsx",
    "pdf",
    "ppt",
    "pptx",
    "png",
    "jpg",
    "jpeg",
    ...bimTypes
  ];
  // const  docType = docTypesMatch(file.name.split(".")[1]).key;
  const docType = file.name.split(".").pop();
  if (docType && !types.includes(docType)) {
    NotifMessage.error("文件格式不支持");
    return;
  }
  try {
    processLoadding.value = true;
    loadProgress.value = 10;
    let fileObj: any = {
      name: file.name,
      fileName: file.name
    };
    let bimInfo = null;
    defaultFileList.value = [fileObj];
    let docId = import.meta.env.VITE_APP_ECM_DOCID;
    const res: any = await importFileForEcm(docId, file.raw);
    if (bimTypes.includes(docType)) {
      bimInfo = await uploadBimFile(file);
    }
    loadProgress.value = 100;
    let timer = setTimeout(() => {
      clearTimeout(timer);
      timer = null;
      processLoadding.value = false;
    }, 500);
    formState.documentName = file.name;
    formState.docType = docTypesMatch(file.name.split(".")[1]).key;
    formState.docTypeName = docTypesMatch(file.name.split(".")[1]).name;
    formState.docSuffix = file.name.split(".")[1];
    fileObj = {
      name: file.name,
      fileName: file.name,
      uuidFile: res.docid,
      fileSize: file.size,
      fileType: formState.docSuffix,
      url: res.rev,
      bimInfo: bimInfo && JSON.stringify(bimInfo)
    };
    defaultFileList.value = [fileObj];
  } catch (e) {
    NotifMessage.error(e?.message);
  }
};

const handlePreview = file => {
  if (file.response) {
    download(file.response.data);
  } else {
    download(file);
  }
};

const handleError = err => {
  console.log(err);
  // let myError = err.toString(); //转字符串
  // myError = myError.replace("Error: ", ""); // 去掉前面的" Error: "
  // if (myError.indexOf('{') !== -1) {
  //   myError = JSON.parse(myError); //转对象
  //   myError?.message && NotifMessage.error(myError?.message);
  // } else {
  //   NotifMessage.error(myError);
  // }
  // if (myError?.body?.code && [401, 403].includes(myError?.body?.code)) {
  //   myError?.body?.message && NotifMessage.error(myError?.body?.message);
  //   router.push("/login");
  //   storageLocal.removeItem("info");
  // }
};

/* 上传 -- end */

// 获取文档类型
const initDoucumentTypeList = async () => {
  const { data } = await api.getTreeDocumentType();
  documentTypeList.value = data;
};

onMounted(async () => {
  initDoucumentTypeList();
  initProjectPhaseList();
});
</script>
<style scoped lang="scss">
.doc-dia {
  :deep .el-upload {
    width: 100%;
  }

  :deep .el-upload-dragger {
    width: 100%;
    height: auto;
    padding: 20px;
    background: #fdfdff;
    border-radius: 4px;

    .el-upload__text {
      font-size: 14px;
      color: #494c53;

      .download-wrap {
        display: flex;
        justify-content: center;

        .download-text {
          display: flex;
          align-items: center;
          text-align: center;
          color: #5298ff;

          a {
            margin: 0 6px;
            font-size: 14px;
            color: #5298ff;
          }

          .icon-wendang {
            font-size: 16px;
          }

          .icon-shanchu {
            color: #e45d5d;
            font-size: 16px;
          }
        }
      }
    }
  }

  .el-upload__tip {
    line-height: 20px;
    text-align: left;
    font-size: 12px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #8895b7;
  }

  .width-custom100 {
    width: 100%;
  }
}
</style>
